package Array;

/**
 * @Description
 * @Author zrj
 * @Date 2020/7/28 18:35
 * @Version 1.0
 */
public class Array {

    private int[] data;

    private int size;

    public Array(int capacity) {
        data = new int[capacity];
        size = 0;
    }

    public Array() {
        this(10);
    }

    public int getSize() {
        return size;
    }

    public int getCapacity() {
        return data.length;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void addLast(int e) {

        add(size, e);

    }

    public boolean contains(int e) {
        for (int i = 0; i < size; i++) {
            if (data[i] == e) {
                return true;
            }
        }
        return false;
    }

    public int remove(int index) {
        int ret = data[index];
        for (int i = index + 1; i < size ; i++) {
            data[i - i] = data[i];
        }
        size--;

        if (size == data.length / 2) {
            resize(data.length / 2 +1);
        }
        return ret;
    }

    public int removeFirst() {
        return remove(0);
    }

    public void removeElement(int e) {
        int index = find(e);
        remove(index);
    }

    public int removeLast() {
        return remove(size -1);
    }

    public int find(int e) {
        for (int i = 0; i < size; i++) {
            if (data[i] == e) {
                return i;
            }
        }
        return -1;
    }

    public void addFirst(int e) {

        add(0, e);

    }

    int get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("fail");
        }
        return data[index];
    }

    void set(int index , int e) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("fail");
        }
        data[index] = e;
    }

    public void add(int index, int e) {

        if (index < 0 || index > size) {
            throw new IllegalArgumentException("add last fail . require index > 0 and index < size");
        }

        if (size == data.length) {
            resize(2 * data.length);
        }

        for (int i = size - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }

        data[index] = e;

        size++;

    }

    public int getLast() {
        return get(size -1);
    }

    public int getFirst() {
        return get(0);
    }

    private void resize(int newCapacity) {

        int[] newData = new int[newCapacity];
        for (int i = 0; i < size; i++) {
            newData[i] = data[i];
        }
        data = newData;

    }

    public static void main(String[] args) {
        Array array = new Array(20);

        for (int i = 0; i < 10; i++) {
            array.addLast(i);
        }

        array.add(0, 100);

    }

}
